package com.clouddms.service.common;

import com.clouddms.entity.FileOperationLog;
import com.clouddms.entity.UserOperationLog;
import com.clouddms.repository.FileOperationLogRepository;
import com.clouddms.repository.UserOperationLogRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class LogService {

    @Autowired
    private UserOperationLogRepository userOperationLogRepository;

    @Autowired
    private FileOperationLogRepository fileOperationLogRepository;

    /**
     * 记录用户操作日志
     */
    public void logUserOperation(Long userId, String operationType, String operation, String details) {
        UserOperationLog log = new UserOperationLog();
        log.setUserId(userId);
        log.setOperationType(operationType);
        log.setOperation(operation);
        log.setOperationDetails(details);
        log.setOperationTime(LocalDateTime.now());
        
        userOperationLogRepository.save(log);
    }

    /**
     * 记录文件操作日志
     */
    public void logFileOperation(Long userId, Long fileId, String operationType, String details) {
        FileOperationLog log = new FileOperationLog();
        log.setUserId(userId);
        log.setFileId(fileId);
        log.setOperationType(operationType);
        log.setOperationDetails(details);
        log.setOperationTime(LocalDateTime.now());
        
        fileOperationLogRepository.save(log);
    }

    /**
     * 获取用户操作日志
     */
    public List<UserOperationLog> getUserOperationLogs(Long userId, int limit) {
        List<UserOperationLog> logs = userOperationLogRepository.findByUserIdOrderByOperationTimeDesc(userId);
        if (limit > 0 && logs.size() > limit) {
            return logs.subList(0, limit);
        }
        return logs;
    }

    /**
     * 获取文件操作日志
     */
    public List<FileOperationLog> getFileOperationLogs(Long fileId) {
        return fileOperationLogRepository.findByFileIdOrderByOperationTimeDesc(fileId);
    }

    /**
     * 根据操作类型获取文件操作日志
     */
    public List<FileOperationLog> getFileOperationLogsByType(String operationType, int limit) {
        List<FileOperationLog> logs = fileOperationLogRepository.findByOperationTypeOrderByOperationTimeDesc(operationType);
        if (limit > 0 && logs.size() > limit) {
            return logs.subList(0, limit);
        }
        return logs;
    }

    /**
     * 获取最近的用户操作日志
     */
    public List<UserOperationLog> getRecentUserOperationLogs(int limit) {
        List<UserOperationLog> logs = userOperationLogRepository.findRecentLogs();
        if (limit > 0 && logs.size() > limit) {
            return logs.subList(0, limit);
        }
        return logs;
    }

    /**
     * 获取最近的文件操作日志
     */
    public List<FileOperationLog> getRecentFileOperationLogs(int limit) {
        List<FileOperationLog> logs = fileOperationLogRepository.findRecentLogs();
        if (limit > 0 && logs.size() > limit) {
            return logs.subList(0, limit);
        }
        return logs;
    }

    /**
     * 获取用户操作统计
     */
    public Map<String, Long> getUserOperationStats(Long userId) {
        Map<String, Long> stats = new HashMap<>();
        
        // 统计各类操作次数
        String[] operationTypes = {"LOGIN", "LOGOUT", "UPLOAD", "DOWNLOAD", "DELETE", "SHARE", "MODIFY"};
        
        for (String type : operationTypes) {
            long count = userOperationLogRepository.countByUserIdAndOperationType(userId, type);
            stats.put(type.toLowerCase(), count);
        }
        
        return stats;
    }

    /**
     * 获取文件操作统计
     */
    public Map<String, Long> getFileOperationStats(Long userId) {
        Map<String, Long> stats = new HashMap<>();
        
        // 统计各类文件操作次数
        String[] operationTypes = {"UPLOAD", "DOWNLOAD", "DELETE", "SHARE", "MODIFY", "RESTORE"};
        
        for (String type : operationTypes) {
            long count = fileOperationLogRepository.countByUserIdAndOperationType(userId, type);
            stats.put(type.toLowerCase(), count);
        }
        
        return stats;
    }

    /**
     * 获取系统操作统计
     */
    public Map<String, Object> getSystemOperationStats() {
        Map<String, Object> stats = new HashMap<>();
        
        // 今日操作统计
        LocalDateTime todayStart = LocalDateTime.now().toLocalDate().atStartOfDay();
        LocalDateTime todayEnd = todayStart.plusDays(1);
        
        long todayUserOps = userOperationLogRepository.countByOperationTimeBetween(todayStart, todayEnd);
        long todayFileOps = fileOperationLogRepository.countByOperationTimeBetween(todayStart, todayEnd);
        
        stats.put("todayUserOperations", todayUserOps);
        stats.put("todayFileOperations", todayFileOps);
        
        // 本周操作统计
        LocalDateTime weekStart = LocalDateTime.now().toLocalDate().atStartOfDay().minusDays(6);
        
        long weekUserOps = userOperationLogRepository.countByOperationTimeBetween(weekStart, todayEnd);
        long weekFileOps = fileOperationLogRepository.countByOperationTimeBetween(weekStart, todayEnd);
        
        stats.put("weekUserOperations", weekUserOps);
        stats.put("weekFileOperations", weekFileOps);
        
        // 文件操作类型分布
        List<Object[]> fileOpTypes = fileOperationLogRepository.countByOperationType();
        Map<String, Long> fileOpTypeStats = new HashMap<>();
        for (Object[] row : fileOpTypes) {
            fileOpTypeStats.put((String) row[0], (Long) row[1]);
        }
        stats.put("fileOperationTypes", fileOpTypeStats);
        
        return stats;
    }

    /**
     * 清理过期日志
     */
    public void cleanupOldLogs(int daysToKeep) {
        LocalDateTime cutoffTime = LocalDateTime.now().minusDays(daysToKeep);
        
        int deletedUserLogs = userOperationLogRepository.deleteByOperationTimeBefore(cutoffTime);
        int deletedFileLogs = fileOperationLogRepository.deleteByOperationTimeBefore(cutoffTime);
        
        // 记录清理操作
        logUserOperation(null, "SYSTEM", "LOG_CLEANUP", 
            String.format("清理过期日志: 用户日志 %d 条, 文件日志 %d 条", deletedUserLogs, deletedFileLogs));
    }

    /**
     * 获取热门文件
     */
    public List<Object[]> getHotFiles(int limit) {
        List<Object[]> files = fileOperationLogRepository.findHotFiles();
        if (limit > 0 && files.size() > limit) {
            return files.subList(0, limit);
        }
        return files;
    }

    /**
     * 获取操作日志按时间范围
     */
    public List<UserOperationLog> getUserOperationLogsByTimeRange(LocalDateTime startTime, LocalDateTime endTime) {
        return userOperationLogRepository.findByOperationTimeBetweenOrderByOperationTimeDesc(startTime, endTime);
    }

    /**
     * 获取文件操作日志按时间范围
     */
    public List<FileOperationLog> getFileOperationLogsByTimeRange(LocalDateTime startTime, LocalDateTime endTime) {
        return fileOperationLogRepository.findByOperationTimeBetweenOrderByOperationTimeDesc(startTime, endTime);
    }
}